package com.example.skytakeoutserver.service

import com.example.skytakeoutserver.data.entity.ShoppingCart
import lombok.RequiredArgsConstructor
import lombok.extern.slf4j.Slf4j
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate
import org.springframework.data.relational.core.query.Criteria
import org.springframework.data.relational.core.query.Query
import org.springframework.data.relational.core.query.isEqual
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono

@Service
@RequiredArgsConstructor
@Slf4j
class ShoppingCartService
    (private val r2dbcEntityTemplate: R2dbcEntityTemplate) {

    /**
     * 分页查询购物车
     */
    fun findShoppingCartByCriteria(
        shoppingCart: ShoppingCart,
    ): Mono<List<ShoppingCart>> {
        var criteria = Criteria.empty()

        shoppingCart.apply {
            userId?.let {
                criteria = criteria
                    .and("user_id")
                    .`is`(it)
            }

            setmealId?.let {
                criteria = criteria
                    .and("setmeal_id").`is`(it)
            }

            dishId?.let {
                criteria = criteria.and("dish_id").`is`(it)
            }

            dishFlavor?.let {
                criteria = criteria.and("dish_flavor").`is`(it)
            }
        }

        val query = Query.query(criteria)

        return r2dbcEntityTemplate
            .select(
                query,
                ShoppingCart::class.java
            )
            .collectList()
    }

}